# -*- coding: utf-8 -*-
import requests,json, logging, time
from tool import prompt, labels_obj
from pprint import pprint
from copy import deepcopy as deepcopy

url = 'http://117.50.174.71:8000/v1/chat/completions'
headers = {
    'accept': 'application/json',
    'Content-Type': 'application/json',
}
# 117.50.174.71

def format_data(content):
    if len(content)>2048:
        content = content[:2040]
    data = {
        "model": "",
        "messages": [
            {
                "role": "user",
                "content": content,
            }
        ],
        "do_sample": True,
        "temperature": 0.1,
        "top_p": 0.1,
        "n": 1,
        "max_tokens": 240,
        "stop": "string",
        "stream": False
    }
    return data

def content_requests(content):
    # print('=====')
    # print(content)
    res = requests.post(
        url, headers=headers, data=json.dumps(format_data(content))
    )
    res = res.json()['choices'][0]['message']['content']

    # print(content)
    # print(res)
    # print('=====')
    res = json.loads(res.replace("'", '"'))
    # logging.info('===============================')
    # logging.info(str(content))
    # logging.info(str(res))
    # logging.info('===============================')
    print('====')
    print(res)
    print('====')
    return res

def first_label_requests(content, type):
    if type=='clarify':
        return content_requests(
            content
        )
    elif type=='purchase':
        return content_requests(
            content
        )
    elif type=='quality':
        return content_requests(
            content
        )
    elif type=='csp':
        return content_requests(
            content
        )
    elif type=='feel':
        return content_requests(
            content
        )
    else:
        logging.info("ERROR : analyze first_label_requests error")

def second_label_requests(content,
                          type,
                          first_label,
                          labels):
    if type=='quality':
        return content_requests(
            prompt._quality_2_prompt(
                customer_voice=content,
                first_label=first_label,
                labels=labels
            )
        )
    elif type=='csp':
        return content_requests(
            prompt._csp_2_prompt(
                customer_voice=content,
                first_label=first_label,
                labels=labels
            )
        )
    else:
        raise RuntimeError('second_label_requests')



def request_content_list(content, label):
    return content_requests(
        prompt._ner_prompt(
            customer_voice=content,
            labels=label
        )
    )

def request_sentiment(content, label):
    return content_requests(
        prompt._sentiment_prompt(
            customer_voice=content,
            content=label
        )
    )

def label_requests(init_voices, type):
    # 摘取客户的原始反馈
    customer_voice = init_voices['customer_voice']

    if type=='convert_voice':
        return init_voices['customer_voice']
    elif type=='clarify':
        """
        判断用户反馈是否和车辆相关
        """
        return first_label_requests(
            content=init_voices['clarify_prompt'],
            type='clarify'
        )
    elif type=='purchase':
        """
        判断客户购买意愿
        """
        return first_label_requests(
            content=init_voices['purchase_prompt'],
            type='purchase'
        )
    elif type=='quality':
        """
        判断客户反馈和车辆质量相关的投诉内容
        """
        first_label_list = first_label_requests(
            content=init_voices['quality_1_prompt'],
            type='quality'
        )
        if '客户反馈不在当前标签列表范围内' in first_label_list:
            first_label_list.remove('客户反馈不在当前标签列表范围内')
        #
        if len(first_label_list):
            res_labels = {_ : [] for _ in first_label_list}
        else:
            res_labels = {}
            return res_labels
        for first_label in first_label_list:
            p_labels = deepcopy(labels_obj.quality_labels[first_label])
            if '客户反馈不在当前标签列表范围内' not in p_labels:
                p_labels.append('客户反馈不在当前标签列表范围内')
            second_label_list = second_label_requests(
                content=customer_voice,
                type='quality',
                first_label=first_label,
                labels=p_labels
            )
            if '客户反馈不在当前标签列表范围内' in second_label_list:
                second_label_list.remove('客户反馈不在当前标签列表范围内')
            for second_label in second_label_list:
                #
                res_labels[first_label].append({second_label : {
                    'content_list' : [],
                    'sentiment' : ''}}
                )
                content_list = request_content_list(
                    content=customer_voice,
                    label=first_label + '-' + second_label,
                )
                res_labels[first_label][-1][second_label]['content_list'] = content_list
                sentiment_list = request_sentiment(
                    content=customer_voice,
                    label=first_label + '-' + second_label,
                )
                if len(sentiment_list)==0:
                    sentiment_list = ['中性情感']
                elif len(sentiment_list)>1:
                    logging.info('ERROR ---> sentiment analysis failure')
                    sentiment_list = sentiment_list[0]
                else:
                    sentiment_list = sentiment_list[0]
                res_labels[first_label][-1][second_label]['sentiment'] = sentiment_list
        return res_labels

    elif type=='csp':
        """
        分析客户 CSP 相关的标签
        """
        first_label_list = first_label_requests(
            content=init_voices['csp_1_prompt'],
            type='csp'
        )
        if '客户反馈不在当前标签列表范围内' in first_label_list:
            first_label_list.remove('客户反馈不在当前标签列表范围内')
        #
        if len(first_label_list):
            res_labels = {_ : [] for _ in first_label_list}
        else:
            res_labels = {}
            return res_labels
        for first_label in first_label_list:
            p_labels = deepcopy(labels_obj.csp_labels[first_label])
            #
            p_labels = list(p_labels.keys())
            if '客户反馈不在当前标签列表范围内' not in p_labels:
                p_labels.append('客户反馈不在当前标签列表范围内')
            second_label_list = second_label_requests(
                content=customer_voice,
                type='csp',
                first_label=first_label,
                labels=p_labels
            )
            if '客户反馈不在当前标签列表范围内' in second_label_list:
                second_label_list.remove('客户反馈不在当前标签列表范围内')
            for second_label in second_label_list:
                #
                res_labels[first_label].append({second_label : {
                    'content_list' : [],
                    'sentiment' : ''}}
                )
                content_list = request_content_list(
                    content=customer_voice,
                    label=first_label + '-' + second_label,
                )
                res_labels[first_label][-1][second_label]['content_list'] = content_list
                sentiment_list = request_sentiment(
                    content=customer_voice,
                    label=first_label + '-' + second_label,
                )
                if len(sentiment_list) == 0:
                    sentiment_list = ['中性情感']
                elif len(sentiment_list) > 1:
                    logging.info('ERROR ---> sentiment analysis failure')
                    sentiment_list = sentiment_list[0]
                else:
                    sentiment_list = sentiment_list[0]
                res_labels[first_label][-1][second_label]['sentiment'] = sentiment_list
        return res_labels

    elif type=='feel':
        """
        分析客户 FEEL 相关的标签
        """
        first_label_list = first_label_requests(
            content=init_voices['feel_1_prompt'],
            type='feel'
        )
        if '客户反馈不在当前标签列表范围内' in first_label_list:
            first_label_list.remove('客户反馈不在当前标签列表范围内')
        #
        if len(first_label_list):
            res_labels = {_ : [
                {
                    'content_list' : [],
                    'sentiment' : ''
                }
            ] for _ in first_label_list}
        else:
            res_labels = {}
            return res_labels
        for first_label in first_label_list:
            content_list = request_content_list(
                content=customer_voice,
                label=first_label ,
            )
            res_labels[first_label][-1]['content_list'] = content_list
            sentiment_list = request_sentiment(
                content=customer_voice,
                label=first_label,
            )
            if len(sentiment_list) == 0:
                sentiment_list = ['中性情感']
            elif len(sentiment_list) > 1:
                logging.info('ERROR ---> sentiment analysis failure')
                sentiment_list = sentiment_list[0]
            else:
                sentiment_list = sentiment_list[0]
            res_labels[first_label][-1]['sentiment'] = sentiment_list
        return res_labels


def callback(sentence):
    sentence = sentence.\
        replace('\r', '').\
        replace('\n', '\n').\
        replace('\t', '')
    res_data = {
        'customer_voice' : '',
        'clarify' : '',
        'purchase': '',
        'quality_label' : '',
        'csp_label' : '',
        'feel_label' : '',
    }

    # 将对应的客户投诉进行一次初步标签处理
    init_voices = prompt.init_preprocess_labels(
        customer_voice=sentence
    )

    # 1. 将客户的原始投诉语句，去除空格等之后装入返回字典
    res_data['customer_voice'] = label_requests(
        init_voices=init_voices,
        type='convert_voice'
    )

    # 2. 判断客户反馈是否和车辆相关
    res_data['clarify'] = label_requests(
        init_voices=init_voices,
        type='clarify'
    )

    # 3. 判断客户购买意愿
    #
    res_data['purchase'] = label_requests(
        init_voices=init_voices,
        type='purchase'
    )

    # 4. 判断客户质量相关
    res_data['quality_label'] = label_requests(
        init_voices=init_voices,
        type='quality'
    )

    # 5. 判断客户CSP相关
    res_data['csp_label'] = label_requests(
        init_voices=init_voices,
        type='csp'
    )


    # 6. 判断客户使用感受相关
    res_data['feel_label'] = label_requests(
        init_voices=init_voices,
        type='feel'
    )

    logging.info('Fianl Result ->  ', str(res_data))
    return res_data

if __name__ == '__main__':
    sentence_1 = "提车使用了一周时间，开了700公里，外观小巧、耐看。内饰只能说够用，智能化感觉还是需要更进一步提高，车机虽然说已经提高了，但是还是有点不“聪明”。低速前后倒车雷达响的头疼，而且是有时候响有时候不响。最奇葩的是等红灯周围没东西乱响。续航目前来说还是比较满意的，日常市区通勤代步平均14.5。休息日跑国道回丈母娘家，来回280公里小长途，平均11左右。车是真好开，提速真快，踩电门就来，网上有人说刹车前段虚，我试了，下坡速度快（60码以上）的时候前段刹车是虚，要深踩和我的老油车一样，但是正常开急加速再急刹没有问题。刹停有异响，就算我很缓慢的刹停还是有一点点声音。门槛有点高，下车有点不习惯。我也不习惯用B档目前都是用D档开。市区充电很方便，我在考虑要不要安装充电桩，电表已经申请安装好了。"
    sentence_2 = """【购车经历】
       五月份换工作以后通勤距离骤增🤣，每天往返160公里，油钱实在是遭不住，正好以前的老车天天高温，跑高速也确实有些乏力了，趁着这个机会，换电车!
       因为不喜欢suv，所以闷头试驾电动轿车，正好秦L上市了，去看了一下，内饰和坐起来的感觉不太喜欢，感觉座椅很软，悬挂也软，虽然很舒服，但是不喜欢这种感觉（因为不久前刚试驾了领克03，从那以后就爱上03的感觉了，要不是油费太贵我就上03了!和秦L完全是两种风格）所以秦L就pass掉了，又去店里试了id3，哦豁？
       不错耶，还真挺好开，虽然没有03那么运动，那么爽，但是也是蛮好开，路感清晰，而且底盘一点不散，不错不错，抓紧给媳妇种草，毕竟这车以后肯定是她的，我还要去换03 or 001嘿嘿，媳妇看了后对我的眼光表示非常的肯定🤣，好!就他了，找了个时间我俩一起去店里看，提前做了谈价攻略，和销售谈了一下午，选了白包，id4的中央扶手，贷款全落地13.1。要了个随车充，送的镀膜，玻璃膜，脚垫。空气净化。当天直接下定!等车!
       大概两周以后，销售打电话说车来了，正好休班带着媳妇一块去提车!办好所有手续开车回家!
       现在开了3200公里了，确实是好开，推背感没多少，但是动力完全够用了，就是电耗确实高😂，但是我天天空调日不落，加上脚法一般，也确实是比较费电的开法，也勉强可以接受，之后我再发一些不同环境条件下的电耗，给要买的朋友一些参考，每天回家晚上充电，通勤是完全够用了。
【最不满意】😠😠😠☹️☹️☹️
         他的玻璃是因为弧度太大还是怎么回事☹️，我开一会就晕车😢，问销售，销售说可能贴了膜就好点，现在贴了膜还是晕，而且好像更严重了，我现在有点怀疑是玻璃的质量问题，就是透过玻璃看外面的物体很不真实，会发生一点点形变，懂车帝的各位大佬们可不可以给老弟支个招，太晕了，看东西很难受，我应该去检测玻璃出个报告还是直接找厂家售后换玻璃啊😕"""

    sentence_3 = """
    
    """


    import json, codecs, time, os
    from pprint import pprint
    from tqdm import tqdm
    sentence = sentence_2

    start_time = time.time()
    res_data = callback(sentence=sentence)
    end_time = time.time()
    print("============")
    pprint(res_data)
    print(end_time - start_time)
    print("============")



    # import json, codecs, time, os
    # from pprint import pprint
    # from tqdm import tqdm
    # new_data = []
    # # TODO : 可能这种大模型自己部署时候会出各种各样的问题，还是直接调llama_factory上面对应的接口吧，远程的调
    # with codecs.open(filename='data/20240825.json', mode='r', encoding='utf-8') as fr:
    #     data = json.load(fr)
    # for d in tqdm(data):
    #     content = d['content'][:1000].replace("\n", "").replace("\r", "").replace("  ", "")
    #     if len(content)<10:
    #         continue
    #     start_time = time.time()
    #     try:
    #         res_data = callback(content)
    #     except:
    #         res_data = {}
    #     end_time = time.time()
    #
    #     d.update({'res' : res_data})
    #     new_data.append(d)
    #     print("=================")
    #     pprint(res_data)
    #     print("Processing Time ", end_time - start_time)
    #     print("=================")
    # with codecs.open(filename='data/20240825-2.json', mode='w', encoding='utf-8') as fw:
    #     json.dump(obj=new_data, fp=fw, ensure_ascii=False, indent=4)
    #
    #



